﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using System.Xml;
using WEBWeixinSDK.Plug;
using WEBWeixinSDK.WXMod;
using static WEBWeixinSDK.HTTP;
using static WEBWeixinSDK.WXInit;
using static WEBWeixinSDK.WXMod.WXMsg;

namespace WEBWeixinSDK
{
    public class Weixin
    {
        public static void Login_Go()
        {
            if (Get_login())
            {
                //1.初始化数据
                Post_init();
                //2.改变微信状态
                Psot_webwxstatusnotif();
                //3.微信同步
                //WxSync();
                //4.获取联系人
                GET_contacrt();
                ExecuteEventLoginStatus(LoginStatus.LoginSuccess);
                //信息处理
                Proc_msg(Weixin.Uin);
                //获取自动回复列表
                //WXsql . GetMsg();

            }

        }
        #region 登录状态

        public enum LoginStatus { LoginSuccess, dlSuccess };
        public delegate void DelegateReceiveLoginStatus(LoginStatus status);
        public static event DelegateReceiveLoginStatus DelegateLoginStatus;
        public static Form formObject;
        public static void ExecuteEventLoginStatus(LoginStatus status)
        {
            try
            {

                if (formObject != null)
                {
                    formObject.Invoke(DelegateLoginStatus, new object[] { status });
                }

            }
            catch (Exception)
            {

                //  throw;
            }

        }
        public static void BELoginStatus(Form form, DelegateReceiveLoginStatus Login)
        {
            formObject = form;
            DelegateLoginStatus += Login;
        }
        #endregion
        /// <summary>
        /// http网络请求实施主体
        /// </summary>
        public static HttpHelper httpClient = new HttpHelper();

        /// <summary>
        /// http请求详细信息，cookies保持者
        /// </summary>
        public static HttpItem httpItem = new HttpItem();
        static string Uuid;
        static int Code = 400;
        /// <summary>
        /// 获取二维码 
        /// </summary>
        /// <returns></returns>
        public static System.Drawing.Image Getjslogin()
        {
            //https://login.wx2.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=&fun=new&lang=zh_CN&_=1531981684792

            string dat = HTTP.Get(string.Format("https://login.wx2.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri={0}&fun=new&lang=zh_CN&_={1}", HttpUtility.UrlEncode("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage"), GetRnd(13)));
            Regex reg = new Regex("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\"");
            var resultreg = reg.Match(dat).Groups;
            if (resultreg.Count == 3)
            {
                Code = int.Parse(resultreg[1].ToString());
                Uuid = resultreg[2].ToString();
            }
            System.Drawing.Image img = null;
            if (Code == 200 && string.IsNullOrEmpty(Uuid) == false)
            {
                img = HTTP.Get_image(string.Format("https://login.weixin.qq.com/qrcode/{0}?t=webwx", Uuid));
            }
            return img;

        }
        /// <summary>
        /// Uin,Sid,Skey,Pass_ticket.微信认真标志，认证完毕获取，以后交互时要使用
        /// </summary>
        public static string Uin;
        public static string Sid;
        public static string Skey;
        public static string DeviceID = "e942350031118103";//e786809990039917
        public static string Pass_ticket;
        public static string Namestr;
        public static string NickNamestr;
        /// <summary>
        /// 当前验证数据字典，大多数post需要该字段
        /// </summary>
        private static Dictionary<string, object> BaseRequest = new Dictionary<string, object>();
        /// <summary>
        /// 切换账号
        /// </summary>
        public static Dictionary<string, Dictionary<string, object>> BaseRequestList = new Dictionary<string, Dictionary<string, object>>();
        private static Dictionary<string, object> Pass_ticketList = new Dictionary<string, object>();

        /// <summary>
        /// 登录成功后获取的返回值对象
        /// </summary>
        private static WXInitRoot WXInit;
        private static Dictionary<string, WXInitRoot> UinWXInit = new Dictionary<string, WXInitRoot>();

        /// <summary>
        /// 登录成功后获取到的重定向地址
        /// </summary>
        private static string mmwebwx = "";
        /// <summary>
        /// 获取当前所有请求的基础字符串，域名部分.带着前缀的
        /// </summary>
        private static string mmwebwxbin = "";
        /// <summary>
        /// 获取的当前请求的主机域名，不带http前缀
        /// </summary>
        private static string mmwebwxhost = "";

        public static void Get_UserLogin()
        {
            int tip = 1;
            //https://login.wx2.qq.com/jslogin?appid=wx782c26e4c19acffb&fun=new&lang=zh_CN&_=1531983197750
            string url = string.Format("https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip={3}&r={1}&_={2}", Uuid, GetRnd(), GetRnd(13), tip);
            int retry_time = 10;
            while (retry_time > 0)
            {
                string html = HTTP.Get(url);
                Regex reg = new Regex("window.code=(\\d+);");
                var resultreg = reg.Match(html).Groups;
                string codeStr = resultreg[1].ToString();
                switch (codeStr)
                {
                    case "201"://已扫描，未确认
                        tip = 0;
                        // SendOnlog("已扫描，未确认");
                        break;
                    case "200"://登录成功
                        SendOnlog("登录成功");
                        //  ExecuteEventLoginStatus(LoginStatus.LoginSuccess);
                        Regex reg1 = new Regex("window.redirect_uri=\"(\\S+?)\";");
                        var resultreg1 = reg1.Match(html).Groups;
                        mmwebwx = resultreg1[1] + "&fun=new";//https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=AyZhSx7FrG1wOBIBr9uEU0fo@qrticket_0&uuid=Qb1IZKYTBg==&lang=zh_CN&scan=1532075511&fun=new
                        mmwebwxbin = mmwebwx.Substring(0, mmwebwx.LastIndexOf('/'));//https://wx2.qq.com/cgi-bin/mmwebwx-bin
                        mmwebwxhost = mmwebwxbin.Substring(8, mmwebwxbin.IndexOf('/', 8) - 8);//wx2.qq.com
                         Login_Go();
                       // ExecuteEventLoginStatus(LoginStatus.LoginSuccess);
                        break;
                    case "408"://超时
                        SendOnlog("超时");
                        retry_time--;
                        break;
                    default:
                        retry_time--;
                        break;
                }
            }


        }

        #region 第一讲微信登录判断，以及改变状态
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        private static bool Get_login()
        {
            bool rs = false;

            if (mmwebwx.Length > 4)
            {
                //获取登录成功后反馈的重定向地址的内容
                string htmlstr = HTTP.Get(mmwebwx);
                if (htmlstr.Contains ("1203"))
                {
                    MessageBox.Show(htmlstr);

                }
                else
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(htmlstr);
                    MemoryStream stream = new MemoryStream(byteArray);
                    XmlReaderSettings settings = new XmlReaderSettings
                    {
                        IgnoreComments = true//忽略文档里面的注释
                    };
                    using (XmlReader reader = XmlReader.Create(stream, settings))
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(reader);
                        XmlNode xn = xmlDoc.SelectSingleNode("error");
                        foreach (XmlNode noneode in xn.ChildNodes)
                        {
                            if (noneode.Name == "skey")
                            {
                                Skey = noneode.ChildNodes[0].InnerText;
                            }
                            else if (noneode.Name == "wxsid")
                            {
                                Sid = noneode.ChildNodes[0].InnerText;
                            }
                            else if (noneode.Name == "wxuin")
                            {
                                Uin = noneode.ChildNodes[0].InnerText;
                            }
                            else if (noneode.Name == "pass_ticket")
                            {
                                Pass_ticket = noneode.ChildNodes[0].InnerText;
                            }
                        }
                        DeviceID = "e" + GetRnd(15);
                        if (WXsql.AllWxuin != null)
                        {
                            if (WXsql.AllWxuin.ContainsKey(Uin))
                            {
                                foreach (var item in WXsql.AllWxuin)
                                {
                                    if (item.Key == Uin)
                                    {
                                        DeviceID = item.Value.ToString();
                                    }
                                }


                            }
                        }


                        BaseRequest = new Dictionary<string, object>
                    {
                        { "Uin", Uin },
                        { "Sid", Sid },
                        { "Skey", Skey },
                        { "DeviceID", DeviceID }
                    };
                        if (!BaseRequestList.ContainsKey(Uin))
                        {
                            BaseRequestList.Add(Uin.ToString(), BaseRequest);
                        }
                        if (!Pass_ticketList.ContainsKey(Uin))
                        {
                            Pass_ticketList.Add(Uin, Pass_ticket);
                        }

                        rs = true;
                    }
                }

              
              
            }
            else
            {
                //   WriteLog("登录失败了");
            }

            return rs;
        }
        /// <summary>
        /// 真.个人信息
        /// </summary>
        public static Dictionary<string, User> TUser;
        public static Dictionary<string, Dictionary<string, User>> UinTUser = new Dictionary<string, Dictionary<string, User>>();


        /// <summary>
        /// 初始化数据
        /// </summary>
        //  public static Dictionary<string, WXInitRoot> Init_Synckey_list = new Dictionary<string, WXInitRoot>();
        private static Dictionary<string, Dictionary<string, string>> SyncKey_list = new Dictionary<string, Dictionary<string, string>>();
        //private static Dictionary<string, SyncKey> SyncKey = new Dictionary<string, SyncKey>();

        /// <summary>
        /// 初始化用户信息
        /// </summary>
        /// <returns></returns>
        private static bool Post_init()
        {
            bool rs = false;
            //https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=1315861662&lang=zh_CN&pass_ticket=LiQCjC2imfcD7L28ggOOT0LjjhUw%252BCJ5xIrXG8puZedEhsUTLQxgw7lgxwlKSJwZ
            string url = mmwebwxbin + string.Format("/webwxinit?r={0}&lang=zh_CN&pass_ticket={1}", Gettime(10000000), Pass_ticket);

            string sendData = string.Format("{{\"BaseRequest\":\"{0}\"}}", BaseRequestList[Uin]);

            string dat = HTTP.Post(url, sendData);
            WXInit = new WXInitRoot();
            //WXInitRoot webwxinit = (WXInitRoot)JsonConvert.DeserializeObject(dat, typeof(WXInitRoot));这个转object int 32太大 太小，没去查原因，换一个写法 
            JavaScriptSerializer jser = new JavaScriptSerializer();
            WXInit = jser.Deserialize<WXInitRoot>(dat);
            if (!UinWXInit.ContainsKey(Uin))
            {
                UinWXInit.Add(Uin, WXInit);
            }
            if (!SyncKey_list.ContainsKey(Uin))
            {
                Dictionary<string, string> Synclist = new Dictionary<string, string>();
                foreach (var item in WXInit.SyncKey.List)
                {
                    Synclist.Add(item.Key.ToString(), item.Val.ToString());
                }
                SyncKey_list.Add(Uin, Synclist);
            }
            if (WXInit != null)
            {
                TUser = new Dictionary<string, User>();
                if (WXInit != null && WXInit.BaseResponse != null)
                {
                    rs = WXInit.BaseResponse.Ret.Equals(0);
                }
                if (WXInit.User != null)
                {
                    if (!TUser.ContainsKey(WXInit.User.UserName))
                    {
                        TUser.Add(WXInit.User.UserName, WXInit.User);
                        //      UinTUser.Add(Uin, TUser);
                        if (!UinTUser.ContainsKey(Uin))
                        {
                            UinTUser.Add(Uin, TUser);
                            Namestr = WXInit.User.UserName;
                            NickNamestr = WXInit.User.NickName;
                        }
                    }

                }
            }

            return rs;
        }
        /// <summary>
        /// 更改状态
        /// </summary>
        /// <returns></returns>
        private static bool Psot_webwxstatusnotif()
        {
            //https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxstatusnotify?lang=zh_CN&pass_ticket=xYkwB%252B%252Bve0IoMY%252BLng%252BvNdCjCd8bDKqzobw2tcsScyNw1lAmJ0OTj6BQ7E0XCj7G
            bool rs = false;
            string url = mmwebwxbin + @"/webwxstatusnotify?lang=zh_CN&pass_ticket=" + Pass_ticket;
            string sendData = string.Format("{{\"BaseRequest\":\"{0}\",\"Code\":\"{1}\",\"FromUserName\":\"{2}\",\"ToUserName\":\"{3}\",\"ClientMsgId\":\"{4}\"}}", BaseRequestList[Uin], 3, WXInit.User.UserName, WXInit.User.UserName, Gettime(10000000));
            string dat = HTTP.Post(url, sendData);

            JavaScriptSerializer jser = new JavaScriptSerializer();
            WXInitRoot curObj = jser.Deserialize<WXInitRoot>(dat);

            if (curObj != null && curObj.BaseResponse != null)
            {
                if (curObj.BaseResponse.Ret.Equals(0))
                {
                    rs = true;
                }
            }

            return rs;
        }
        #region 获取随机数
        /// <summary>
        /// 获取随机数
        /// </summary>
        /// <param name="len">随机数长度1-10</param>
        /// <returns></returns>
        public static string GetRnd(int len = 10)
        {
            string str = "";

            Random rd = new Random();
            string strrnd = rd.Next().ToString() + rd.Next().ToString();

            if (len > 0 && len <= strrnd.Length)
            {
                str = strrnd.Substring(0, len);
            }
            else if (len == 10)
            {
                str = strrnd.Substring(0, 10);
            }
            else if (len > 10 && len < 20)
            {
                str = strrnd.Substring(0, len - 10) + strrnd.Substring(0, 10);
            }
            return str;
        }

        /// <summary>
        /// 获取UTC标准时差毫秒
        /// </summary>
        /// <returns>返回标准时间字符串</returns>
        private static string Gettime(long n = 10000)
        {
            DateTime dt = new DateTime(1970, 1, 1);
            return ((DateTime.UtcNow - dt).Ticks / n).ToString();
        }
        #endregion

        #region 日志

        /// <summary>
        /// 委托消息
        /// </summary>
        /// <param name="messages">msg</param>
        /// <param name="onlogtf">0.默认系统 1.好友 2.群 3.讨论组 4.自定义</param>
        /// <param name="qq">qq</param>
        /// <param name="qun">qun</param>
        public static void SendOnlog(string messages, int onlogtf = 0, string qq = "0", string qun = "0")
        {
            try
            {

                if (onlogtf == 1)//好友
                {
                    SysOnlog("\r\n" + DateTime.Now.ToString() + "收到 "
                          + "【" + qq + "】的私聊消息：" + messages.Trim());
                }
                else if (onlogtf == 2)//群
                {
                    SysOnlog("\r\n" + DateTime.Now.ToString() + "收到 " + "【" + qun + "】" + " 群聊，群员 "
                           + "【" + qq + "】的群消息：" + messages.Trim());
                }
                else if (onlogtf == 3)//讨论组
                {
                    SysOnlog("\r\n" + DateTime.Now.ToString() + "收到 " + "【" + qun + "】" + " 讨论组， 组员 "
                            + "【" + qq + "】的讨论消息：" + messages.Trim());
                }
                else if (onlogtf == 0)//系统
                {
                    SysOnlog("\r\n" + DateTime.Now.ToString() + "收到 【系统消息】" + messages.Trim());
                }
                else if (onlogtf == 4)//自定义
                {
                    SysOnlog(messages);
                }
            }
            catch (Exception)
            {

                //throw;
            }

        }
        public static void SysOnlog(string messages)
        {
            SysLog.GetInstance().AddLog(messages);

        }
        #endregion
        /// <summary>
        /// 公众号
        /// </summary>
        public static Dictionary<string, MemberGroup> Group;
        /// <summary>
        /// 公众号列表
        /// </summary>
        public static Dictionary<string, Dictionary<string, MemberGroup>> UinGroup = new Dictionary<string, Dictionary<string, MemberGroup>>();
        /// <summary>
        /// 好友信息
        /// </summary>
        public static Dictionary<string, MemUser> User = new Dictionary<string, MemUser>();
        /// <summary>
        /// 好友信息列表
        /// </summary>
        public static Dictionary<string, Dictionary<string, MemUser>> UinUser = new Dictionary<string, Dictionary<string, MemUser>>();

        /// <summary>
        /// 群聊信息
        /// </summary>
        public static Dictionary<string, GroupChat> Chat = new Dictionary<string, GroupChat>();
        /// <summary>
        /// 群聊消息列表
        /// </summary>
        public static Dictionary<string, Dictionary<string, GroupChat>> UinChat = new Dictionary<string, Dictionary<string, GroupChat>>();

        /// <summary>
        /// 其他信息
        /// </summary>
        public static Dictionary<string, OtherMem> OtherMe = new Dictionary<string, OtherMem>();
        /// <summary>
        /// 其他应用列表
        /// </summary>
        public static Dictionary<string, Dictionary<string, OtherMem>> UinOtherMe = new Dictionary<string, Dictionary<string, OtherMem>>();

        #endregion

        #region 第二讲获取 联系人  公总号  群聊 好友  信息
        /// <summary>
        /// 同步数据
        /// </summary>
        private static Dictionary<string, WXSync2> WxSyncmen = new Dictionary<string, WXSync2>();
        /// <summary>
        /// 请求联系人 公总号 群聊信息
        /// </summary>
        /// <returns></returns>
        private static bool GET_contacrt()
        {
            bool rs = false;
            string url = string.Format(mmwebwxbin + "/webwxgetcontact?pass_ticket={0}&skey={1}&r={2}", Pass_ticket, Skey, Gettime(10000000));
            string dat = HTTP.Post(url, "");
            JavaScriptSerializer jser = new JavaScriptSerializer();
            wxMemberObj = jser.Deserialize<WXMember>(dat);
            if (wxMemberObj != null && wxMemberObj.BaseResponse != null)
            {
                wxMemberObj.SortMembers();
                rs = wxMemberObj.BaseResponse.Ret.Equals(0);
            }
            WXMember inf = wxMemberObj;

            #region MyRegion

            if (inf.GroupMember.Count >= 0)
            {
                Chat = new Dictionary<string, GroupChat>();
                for (int i = 0; i < inf.GroupMember.Count; i++)
                {
                    if (!Chat.ContainsKey(inf.GroupMember[i].UserName.ToString()))
                    {
                        Chat.Add(inf.GroupMember[i].UserName.ToString(), new GroupChat());
                    }
                    Chat[inf.GroupMember[i].UserName.ToString()].Alias = inf.GroupMember[i].Alias; Chat[inf.GroupMember[i].UserName.ToString()].AppAccountFlag = inf.GroupMember[i].AppAccountFlag;
                    Chat[inf.GroupMember[i].UserName.ToString()].AttrStatus = inf.GroupMember[i].AttrStatus; Chat[inf.GroupMember[i].UserName.ToString()].HideInputBarFlag = inf.GroupMember[i].HideInputBarFlag;
                    Chat[inf.GroupMember[i].UserName.ToString()].ChatRoomId = inf.GroupMember[i].ChatRoomId; Chat[inf.GroupMember[i].UserName.ToString()].IsOwner = inf.GroupMember[i].IsOwner;
                    Chat[inf.GroupMember[i].UserName.ToString()].City = inf.GroupMember[i].City; Chat[inf.GroupMember[i].UserName.ToString()].KeyWord = inf.GroupMember[i].KeyWord;
                    Chat[inf.GroupMember[i].UserName.ToString()].ContactFlag = inf.GroupMember[i].ContactFlag; Chat[inf.GroupMember[i].UserName.ToString()].MemberCount = inf.GroupMember[i].MemberCount;
                    Chat[inf.GroupMember[i].UserName.ToString()].DisplayName = inf.GroupMember[i].DisplayName; Chat[inf.GroupMember[i].UserName.ToString()].NickName = inf.GroupMember[i].NickName;
                    Chat[inf.GroupMember[i].UserName.ToString()].EncryChatRoomId = inf.GroupMember[i].EncryChatRoomId; Chat[inf.GroupMember[i].UserName.ToString()].OwnerUin = inf.GroupMember[i].OwnerUin;
                    Chat[inf.GroupMember[i].UserName.ToString()].HeadImgUrl = inf.GroupMember[i].HeadImgUrl; Chat[inf.GroupMember[i].UserName.ToString()].PYInitial = inf.GroupMember[i].PYInitial;
                    Chat[inf.GroupMember[i].UserName.ToString()].PYQuanPin = inf.GroupMember[i].PYQuanPin; Chat[inf.GroupMember[i].UserName.ToString()].RemarkPYInitial = inf.GroupMember[i].RemarkPYInitial;
                    Chat[inf.GroupMember[i].UserName.ToString()].RemarkName = inf.GroupMember[i].RemarkName; Chat[inf.GroupMember[i].UserName.ToString()].RemarkPYQuanPin = inf.GroupMember[i].RemarkPYQuanPin;
                    Chat[inf.GroupMember[i].UserName.ToString()].Sex = inf.GroupMember[i].Sex; Chat[inf.GroupMember[i].UserName.ToString()].SnsFlag = inf.GroupMember[i].SnsFlag;
                    Chat[inf.GroupMember[i].UserName.ToString()].Signature = inf.GroupMember[i].Signature; Chat[inf.GroupMember[i].UserName.ToString()].StarFriend = inf.GroupMember[i].StarFriend;
                    Chat[inf.GroupMember[i].UserName.ToString()].Statues = inf.GroupMember[i].Statues; Chat[inf.GroupMember[i].UserName.ToString()].Uin = inf.GroupMember[i].Uin;
                    Chat[inf.GroupMember[i].UserName.ToString()].UniFriend = inf.GroupMember[i].UniFriend; Chat[inf.GroupMember[i].UserName.ToString()].UserName = inf.GroupMember[i].UserName;
                    Chat[inf.GroupMember[i].UserName.ToString()].VerifyFlag = inf.GroupMember[i].VerifyFlag;

                }
                if (!UinChat.ContainsKey(Uin))
                {
                    UinChat.Add(Uin, Chat);
                }

            }


            if (inf.NormalMember.Count >= 0)
            {
                User = new Dictionary<string, MemUser>();
                for (int i = 0; i < inf.NormalMember.Count; i++)
                {
                    if (!User.ContainsKey(inf.NormalMember[i].UserName.ToString()))
                    {
                        User.Add(inf.NormalMember[i].UserName.ToString(), new MemUser());
                    }
                    User[inf.NormalMember[i].UserName.ToString()].Alias = inf.NormalMember[i].Alias; User[inf.NormalMember[i].UserName.ToString()].AppAccountFlag = inf.NormalMember[i].AppAccountFlag;
                    User[inf.NormalMember[i].UserName.ToString()].AttrStatus = inf.NormalMember[i].AttrStatus; User[inf.NormalMember[i].UserName.ToString()].HideInputBarFlag = inf.NormalMember[i].HideInputBarFlag;
                    User[inf.NormalMember[i].UserName.ToString()].ChatRoomId = inf.NormalMember[i].ChatRoomId; User[inf.NormalMember[i].UserName.ToString()].IsOwner = inf.NormalMember[i].IsOwner;
                    User[inf.NormalMember[i].UserName.ToString()].City = inf.NormalMember[i].City; User[inf.NormalMember[i].UserName.ToString()].KeyWord = inf.NormalMember[i].KeyWord;
                    User[inf.NormalMember[i].UserName.ToString()].ContactFlag = inf.NormalMember[i].ContactFlag; User[inf.NormalMember[i].UserName.ToString()].MemberCount = inf.NormalMember[i].MemberCount;
                    User[inf.NormalMember[i].UserName.ToString()].DisplayName = inf.NormalMember[i].DisplayName; User[inf.NormalMember[i].UserName.ToString()].NickName = inf.NormalMember[i].NickName;
                    User[inf.NormalMember[i].UserName.ToString()].EncryChatRoomId = inf.NormalMember[i].EncryChatRoomId; User[inf.NormalMember[i].UserName.ToString()].OwnerUin = inf.NormalMember[i].OwnerUin;
                    User[inf.NormalMember[i].UserName.ToString()].HeadImgUrl = inf.NormalMember[i].HeadImgUrl; User[inf.NormalMember[i].UserName.ToString()].PYInitial = inf.NormalMember[i].PYInitial;
                    User[inf.NormalMember[i].UserName.ToString()].PYQuanPin = inf.NormalMember[i].PYQuanPin; User[inf.NormalMember[i].UserName.ToString()].RemarkPYInitial = inf.NormalMember[i].RemarkPYInitial;
                    User[inf.NormalMember[i].UserName.ToString()].RemarkName = inf.NormalMember[i].RemarkName; User[inf.NormalMember[i].UserName.ToString()].RemarkPYQuanPin = inf.NormalMember[i].RemarkPYQuanPin;
                    User[inf.NormalMember[i].UserName.ToString()].Sex = inf.NormalMember[i].Sex; User[inf.NormalMember[i].UserName.ToString()].SnsFlag = inf.NormalMember[i].SnsFlag;
                    User[inf.NormalMember[i].UserName.ToString()].Signature = inf.NormalMember[i].Signature; User[inf.NormalMember[i].UserName.ToString()].StarFriend = inf.NormalMember[i].StarFriend;
                    User[inf.NormalMember[i].UserName.ToString()].Statues = inf.NormalMember[i].Statues; User[inf.NormalMember[i].UserName.ToString()].Uin = inf.NormalMember[i].Uin;
                    User[inf.NormalMember[i].UserName.ToString()].UniFriend = inf.NormalMember[i].UniFriend; User[inf.NormalMember[i].UserName.ToString()].UserName = inf.NormalMember[i].UserName;
                    User[inf.NormalMember[i].UserName.ToString()].VerifyFlag = inf.NormalMember[i].VerifyFlag;

                }
                //         
                if (!UinUser.ContainsKey(Uin))
                {
                    UinUser.Add(Uin, User);
                }
            }

            if (inf.PublicMember.Count >= 0)
            {
                Group = new Dictionary<string, MemberGroup>();
                for (int i = 0; i < inf.PublicMember.Count; i++)
                {
                    if (!Group.ContainsKey(inf.PublicMember[i].UserName.ToString()))
                    {
                        Group.Add(inf.PublicMember[i].UserName.ToString(), new MemberGroup());
                    }
                    Group[inf.PublicMember[i].UserName.ToString()].Alias = inf.PublicMember[i].Alias; Group[inf.PublicMember[i].UserName.ToString()].AppAccountFlag = inf.PublicMember[i].AppAccountFlag;
                    Group[inf.PublicMember[i].UserName.ToString()].AttrStatus = inf.PublicMember[i].AttrStatus; Group[inf.PublicMember[i].UserName.ToString()].HideInputBarFlag = inf.PublicMember[i].HideInputBarFlag;
                    Group[inf.PublicMember[i].UserName.ToString()].ChatRoomId = inf.PublicMember[i].ChatRoomId; Group[inf.PublicMember[i].UserName.ToString()].IsOwner = inf.PublicMember[i].IsOwner;
                    Group[inf.PublicMember[i].UserName.ToString()].City = inf.PublicMember[i].City; Group[inf.PublicMember[i].UserName.ToString()].KeyWord = inf.PublicMember[i].KeyWord;
                    Group[inf.PublicMember[i].UserName.ToString()].ContactFlag = inf.PublicMember[i].ContactFlag; Group[inf.PublicMember[i].UserName.ToString()].MemberCount = inf.PublicMember[i].MemberCount;
                    Group[inf.PublicMember[i].UserName.ToString()].DisplayName = inf.PublicMember[i].DisplayName; Group[inf.PublicMember[i].UserName.ToString()].NickName = inf.PublicMember[i].NickName;
                    Group[inf.PublicMember[i].UserName.ToString()].EncryChatRoomId = inf.PublicMember[i].EncryChatRoomId; Group[inf.PublicMember[i].UserName.ToString()].OwnerUin = inf.PublicMember[i].OwnerUin;
                    Group[inf.PublicMember[i].UserName.ToString()].HeadImgUrl = inf.PublicMember[i].HeadImgUrl; Group[inf.PublicMember[i].UserName.ToString()].PYInitial = inf.PublicMember[i].PYInitial;
                    Group[inf.PublicMember[i].UserName.ToString()].PYQuanPin = inf.PublicMember[i].PYQuanPin; Group[inf.PublicMember[i].UserName.ToString()].RemarkPYInitial = inf.PublicMember[i].RemarkPYInitial;
                    Group[inf.PublicMember[i].UserName.ToString()].RemarkName = inf.PublicMember[i].RemarkName; Group[inf.PublicMember[i].UserName.ToString()].RemarkPYQuanPin = inf.PublicMember[i].RemarkPYQuanPin;
                    Group[inf.PublicMember[i].UserName.ToString()].Sex = inf.PublicMember[i].Sex; Group[inf.PublicMember[i].UserName.ToString()].SnsFlag = inf.PublicMember[i].SnsFlag;
                    Group[inf.PublicMember[i].UserName.ToString()].Signature = inf.PublicMember[i].Signature; Group[inf.PublicMember[i].UserName.ToString()].StarFriend = inf.PublicMember[i].StarFriend;
                    Group[inf.PublicMember[i].UserName.ToString()].Statues = inf.PublicMember[i].Statues; Group[inf.PublicMember[i].UserName.ToString()].Uin = inf.PublicMember[i].Uin;
                    Group[inf.PublicMember[i].UserName.ToString()].UniFriend = inf.PublicMember[i].UniFriend; Group[inf.PublicMember[i].UserName.ToString()].UserName = inf.PublicMember[i].UserName;
                    Group[inf.PublicMember[i].UserName.ToString()].VerifyFlag = inf.PublicMember[i].VerifyFlag;

                }
                if (!UinGroup.ContainsKey(Uin))
                {
                    UinGroup.Add(Uin, Group);
                }
                //      
            }
            if (inf.OtherMember.Count >= 0)
            {
                OtherMe = new Dictionary<string, OtherMem>();
                for (int i = 0; i < inf.OtherMember.Count; i++)
                {

                    if (!OtherMe.ContainsKey(inf.OtherMember[i].UserName.ToString()))
                    {
                        OtherMe.Add(inf.OtherMember[i].UserName.ToString(), new OtherMem());
                    }
                    OtherMe[inf.OtherMember[i].UserName.ToString()].Alias = inf.OtherMember[i].Alias; OtherMe[inf.OtherMember[i].UserName.ToString()].AppAccountFlag = inf.OtherMember[i].AppAccountFlag;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].AttrStatus = inf.OtherMember[i].AttrStatus; OtherMe[inf.OtherMember[i].UserName.ToString()].HideInputBarFlag = inf.OtherMember[i].HideInputBarFlag;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].ChatRoomId = inf.OtherMember[i].ChatRoomId; OtherMe[inf.OtherMember[i].UserName.ToString()].IsOwner = inf.OtherMember[i].IsOwner;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].City = inf.OtherMember[i].City; OtherMe[inf.OtherMember[i].UserName.ToString()].KeyWord = inf.OtherMember[i].KeyWord;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].ContactFlag = inf.OtherMember[i].ContactFlag; OtherMe[inf.OtherMember[i].UserName.ToString()].MemberCount = inf.OtherMember[i].MemberCount;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].DisplayName = inf.OtherMember[i].DisplayName; OtherMe[inf.OtherMember[i].UserName.ToString()].NickName = inf.OtherMember[i].NickName;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].EncryChatRoomId = inf.OtherMember[i].EncryChatRoomId; OtherMe[inf.OtherMember[i].UserName.ToString()].OwnerUin = inf.OtherMember[i].OwnerUin;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].HeadImgUrl = inf.OtherMember[i].HeadImgUrl; OtherMe[inf.OtherMember[i].UserName.ToString()].PYInitial = inf.OtherMember[i].PYInitial;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].PYQuanPin = inf.OtherMember[i].PYQuanPin; OtherMe[inf.OtherMember[i].UserName.ToString()].RemarkPYInitial = inf.OtherMember[i].RemarkPYInitial;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].RemarkName = inf.OtherMember[i].RemarkName; OtherMe[inf.OtherMember[i].UserName.ToString()].RemarkPYQuanPin = inf.OtherMember[i].RemarkPYQuanPin;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].Sex = inf.OtherMember[i].Sex; OtherMe[inf.OtherMember[i].UserName.ToString()].SnsFlag = inf.OtherMember[i].SnsFlag;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].Signature = inf.OtherMember[i].Signature; OtherMe[inf.OtherMember[i].UserName.ToString()].StarFriend = inf.OtherMember[i].StarFriend;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].Statues = inf.OtherMember[i].Statues; OtherMe[inf.OtherMember[i].UserName.ToString()].Uin = inf.OtherMember[i].Uin;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].UniFriend = inf.OtherMember[i].UniFriend; OtherMe[inf.OtherMember[i].UserName.ToString()].UserName = inf.OtherMember[i].UserName;
                    OtherMe[inf.OtherMember[i].UserName.ToString()].VerifyFlag = inf.OtherMember[i].VerifyFlag;

                }
                if (!UinOtherMe.ContainsKey(Uin))
                {
                    UinOtherMe.Add(Uin, OtherMe);
                }

            }


            #endregion

            Post_group_members();

            return rs;
        }
        /// <summary>
        /// 群聊成员信息
        /// </summary>
        public static Dictionary<string, GroupChatUser> GroupUser;
        /// <summary>
        /// 群成员列表
        /// </summary>
        public static Dictionary<string, Dictionary<string, GroupChatUser>> UinGroupUser = new Dictionary<string, Dictionary<string, GroupChatUser>>();

        /// <summary>
        /// 获取到的群列表
        /// </summary>
        private static WebWXGroupuserList GroupList;
        /// <summary>
        /// 
        /// </summary>
        public static Dictionary<string, Dictionary<string, WebWXGroupuserList>> UinGroupList = new Dictionary<string, Dictionary<string, WebWXGroupuserList>>();

        /// <summary>
        /// 请求群用户信息
        /// </summary>
        private static void Post_group_members()
        {
            // https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r=1532354424566&lang=zh_CN&pass_ticket=JOAhhdbtxaZLCOURZ7
            string url = string.Format("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r={0}&lang=zh_CN&pass_ticket={1}", Gettime(10000000), Pass_ticket);
            List<object> allGroupList = new List<object>();
            foreach (MemberObj oneGroup in wxMemberObj.GroupMember)
            {
                Dictionary<string, object> DicGroup = new Dictionary<string, object>
                {
                    { "UserName", oneGroup.UserName },
                    { "ChatRoomId", "" }
                };
                allGroupList.Add(DicGroup);
            }
            string sendData = string.Format("{{\"BaseRequest\":{0},\"Count\":{1},\"List\":{2}}}", ToJson(BaseRequestList[Uin]), ToJson(wxMemberObj.GroupMember.Count), ToJson(allGroupList));
            string htmlStr = HTTP.Post(url, sendData);
            JavaScriptSerializer jser = new JavaScriptSerializer();
            GroupList = jser.Deserialize<WebWXGroupuserList>(htmlStr);
            if (GroupList != null && GroupList.Count >= 0)
            {
                GroupUser = new Dictionary<string, GroupChatUser>();
                for (int i = 0; i < GroupList.Count; i++)
                {

                    if (!GroupUser.ContainsKey(GroupList.ContactList[i].UserName))
                    {
                        GroupUser.Add(GroupList.ContactList[i].UserName, GroupList.ContactList[i]);

                    }
                }
                if (!UinGroupUser.ContainsKey(Uin))
                {
                    UinGroupUser.Add(Uin, GroupUser);
                }
                // 
            }
        }
        /// <summary>
        /// 微信同步
        /// </summary>
        /// <returns></returns> 
        public static void WxSync()
        {
            ////https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid={0}&skey={1}&lang=zh_CN&pass_ticket={2}
            //string url = string.Format("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid={0}&skey={1}&lang=zh_CN&pass_ticket={2}", Sid, Skey, Pass_ticket);

            //string sendData = string.Format("{{\"BaseRequest\":\"{0}\",\"SyncKey\":\"{1}\",\"rr\":\"{2}\"}}", BaseRequestList[Uin], Get_Sync_key_str(), GetRnd());
            ////第一次同步
            //string dat = HTTP.Post(url, sendData);

            //WXSync wxsync = (WXSync)JsonConvert.DeserializeObject(dat, typeof(WXSync));

            //sendData = string.Format("{{\"BaseRequest\":\"{0}\",\"SyncKey\":\"{1}\",\"rr\":\"{2}\"}}", BaseRequestList[Uin], wxsync, GetRnd());
            ////第二次同步
            //string dat2 = HTTP.Post(url, sendData);

            //WXSync2 wxsync2 = (WXSync2)JsonConvert.DeserializeObject(dat2, typeof(WXSync2));
            //WxSyncmen.Add(Uin, wxsync2);
        }
        #endregion

        #region 第三讲 消息处理， 

        /// <summary>
        /// 是否要终止获取消息的线程
        /// </summary>
        private static bool isStop = false;
        /// <summary>
        /// 通过SyncKey数组获取一个认证字符串
        /// </summary>
        /// <returns></returns>
        private static string Get_Sync_key_str(string uinstr)
        {
            string str = "";
            foreach (var Uinitem in UinWXInit)
            {
                if (Uinitem.Key == uinstr)
                {
                    if (Uinitem.Value != null && Uinitem.Value.SyncKey != null && Uinitem.Value.SyncKey.List != null)
                    {
                        foreach (var oneitem in Uinitem.Value.SyncKey.List)
                        {
                            if (string.IsNullOrEmpty(str))
                            {
                                str += oneitem.Key.ToString() + "_" + oneitem.Val.ToString();
                            }
                            else
                            {
                                str += "|" + oneitem.Key.ToString() + "_" + oneitem.Val.ToString();
                            }
                        }
                    }
                    //if (WXInit != null && WXInit.SyncKey != null && WXInit.SyncKey.List != null)
                    //{
                    //    foreach (var oneitem in WXInit.SyncKey.List)
                    //    {
                    //        if (string.IsNullOrEmpty(str))
                    //        {
                    //            str += oneitem.Key.ToString() + "_" + oneitem.Val.ToString();
                    //        }
                    //        else
                    //        {
                    //            str += "|" + oneitem.Key.ToString() + "_" + oneitem.Val.ToString();
                    //        }
                    //    }
                    //}
                }
            }
            return str;
        }
        /// <summary>
        /// 向服务器进行消息扫描
        /// </summary>
        /// <returns></returns>
        private static int[] Sync_check(string uinmsg)
        {
            int[] rs = new int[] { -1, -1 };
            try
            {              
                foreach (var brlist in BaseRequestList)
                {
                    if (brlist.Key == uinmsg)
                    {
                        string url = string.Format("https://webpush.wx2.qq.com/cgi-bin/mmwebwx-bin/synccheck?r={0}&skey={1}&sid={2}&uin={3}&deviceid={4}&synckey={5}&_={6}"
                            , GetRnd(), brlist.Value["Skey"], brlist.Value["Sid"], brlist.Value["Uin"], brlist.Value["DeviceID"], Get_Sync_key_str(uinmsg), GetRnd());

                        string htmlstr = HTTP.Get(url);
                     //   SendOnlog(htmlstr);
                        //window.synccheck={retcode:\"0\",selector:\"2\"}
                        Regex reg = new Regex("window.synccheck={retcode:\"(\\d+)\",selector:\"(\\d+)\"}");
                        var resultreg = reg.Match(htmlstr).Groups;
                        if (resultreg.Count == 3)
                        {
                            try
                            {
                                rs[0] = int.Parse(resultreg[1].ToString());
                                rs[1] = int.Parse(resultreg[2].ToString());
                            }
                            catch { }
                        }
                    }

                }
              
            }
            catch (Exception)
            {

                //throw;
            }
            return rs;
        }

        /// <summary>
        /// 获取服务器当前产生的消息
        /// </summary>
        /// <returns>消息对象</returns>
        private static WXMsg.WebWXSyncObj Syncmsg()
        {
            string sync_url = mmwebwxbin + "/webwxsync?sid={0}&skey={1}&lang=en_US&pass_ticket={2}";
            sync_url = string.Format(sync_url, Sid, Skey, Pass_ticket);
            ;
            string sendData = string.Format("{{\"BaseRequest\":{0},\"SyncKey\":{1},\"rr\":{2}}}", ToJson(BaseRequestList[Uin]), ToJson(WXInit.SyncKey), ~long.Parse(Gettime(10000000)));

            string htmlStr = HTTP.Post(sync_url, sendData);
     //       SendOnlog(htmlStr);
            JavaScriptSerializer jser = new JavaScriptSerializer();
            WXMsg.WebWXSyncObj wxMsgObj = null;

            try
            {
                wxMsgObj = jser.Deserialize<WXMsg.WebWXSyncObj>(htmlStr);
            }
            catch { }
            ///去重
            if (wxMsgObj != null && wxMsgObj.BaseResponse != null && wxMsgObj.BaseResponse.Ret.Equals(0))
            {
                WXInit.SyncKey = wxMsgObj.SyncKey;
            }

            return wxMsgObj;
        }

        /// <summary>
        /// 获取到的用户列表
        /// </summary>
        private static WXMember wxMemberObj;
        /// <summary>
        /// 通过用户id获取用户信息
        /// </summary>
        /// <param name="_userId">用户id</param>
        /// <returns>用户详细信息</returns>
        private static MemberObj FindMemberInfoById(string _userId)
        {
            if (wxMemberObj != null && wxMemberObj.MemberList != null)
            {
                foreach (MemberObj oneUser in wxMemberObj.MemberList)
                {
                    if (oneUser.UserName.Equals(_userId))
                    {
                        return oneUser;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 从原始消息得到我们想要的消息类型
        /// </summary>
        /// <param name="oneMsg">原始消息</param>
        /// <returns>重新封装的消息</returns>
        private static WXItinMsg GetWXMsgFormOriMsg(WXMsg.AddMsgList oneMsg)
        {
            if (string.IsNullOrEmpty(oneMsg.FromUserName) == false)
            {
                WXItinMsg rs = new WXItinMsg();
                if (oneMsg.FromUserName.IndexOf("@@") == 0)///群
                {
                    foreach (var oneGroup in GroupList.ContactList)
                    {
                        if (oneGroup.UserName.Equals(oneMsg.FromUserName))
                        {
                            rs.From = oneGroup.GetDisName();
                            int ntemp = oneMsg.Content.IndexOf(":");
                            if (ntemp != -1)///群里面的正常消息，Content结构为"用户ID:消息内容"
                            {
                                string usrNameStr = oneMsg.Content.Substring(0, ntemp);
                                oneMsg.Content = oneMsg.Content.Substring(ntemp + 1);
                                foreach (var oneUser in oneGroup.MemberList)
                                {
                                    if (oneUser.UserName.Equals(usrNameStr))
                                    {
                                        rs.From2 = oneUser.GetDisName();
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                else if (oneMsg.FromUserName.IndexOf("@") == 0)///一般用户消息
                {
                    foreach (var oneUser in wxMemberObj.MemberList)
                    {
                        if (oneUser.UserName.Equals(oneMsg.FromUserName))
                        {
                            rs.From = oneUser.GetDisName();
                            break;
                        }
                    }
                    //SendOnlog(rs.Msg,1, rs.From);
                }
                else if (string.IsNullOrEmpty(rs.From))
                {
                    rs.From = oneMsg.FromUserName;
                }

                ///消息内容解析
                GetMessgeContent(oneMsg, rs);
                rs.Type = oneMsg.MsgType;
                rs.Time = DateTime.Now;
             
                return rs;
            }
            return null;
        }
        /// <summary>
        /// 解析消息内容
        /// </summary>
        /// <param name="msg">原始消息</param>
        /// <param name="oneMsg">解析后的消息</param>
        private static void GetMessgeContent(WXMsg.AddMsgList msg, WXItinMsg oneMsg)
        {
            if (string.IsNullOrEmpty(msg.FromUserName))
            {
                return;
            }
            string str = msg.Content;

            switch (msg.MsgType)
            {
                case 1://文本消息
                    if (msg.SubMsgType == 48)//位置信息
                    {
                        str = msg.OriContent;
                        oneMsg.Url = URLDecode(msg.Url);
                    }
                    else
                    {
                        str = msg.Content.Replace("<br/>", "");
                    }
                    break;
                case 3://图片消息
                case 47://动画表情
                    string imageUrl = mmwebwxbin + @"/webwxgetmsgimg?msgid={0}&skey={1}";
                    imageUrl = string.Format(imageUrl, msg.MsgId, Skey);
                    str = SaveURLHTMLObject(imageUrl, 3);
                    if (string.IsNullOrEmpty(str))
                    {
                        str = "系统表情无法获取";
                    }
                    break;
                case 34://语音消息
                    string voiceUrl = mmwebwxbin + @"/webwxgetvoice?msgid={0}&skey={1}";
                    voiceUrl = string.Format(voiceUrl, msg.MsgId, Skey);
                    str = SaveURLHTMLObject(voiceUrl, 34);
                    break;
                case 49://分享
                    str = msg.FileName;
                    oneMsg.Url = URLDecode(msg.Url);
                    break;
                case 43://小视频
                case 62://小视频
                    string videoUrl = mmwebwxbin + @"/webwxgetvideo?msgid={0}&skey={1}&type=flv";
                    videoUrl = string.Format(videoUrl, msg.MsgId, Skey);
                    str = SaveURLHTMLObject(videoUrl, 62);
                    break;
                default:
                    str = msg.Content;
                    break;
            }
            if ( !string .IsNullOrEmpty (oneMsg.From)&& !string.IsNullOrEmpty(oneMsg.From2))
            {
                SendOnlog(str, 2, oneMsg.From2, oneMsg.From);

            }
            else
            {
                SendOnlog(str, 1, oneMsg.From);

            }
            oneMsg.Msg = str;
        }
        /// <summary>
        /// 根据类别保存连接对象内容到本地
        /// </summary>
        /// <param name="urlBase">请求连接</param>
        /// <param name="msgType">类型</param>
        /// <returns>保存地址</returns>
        private static string SaveURLHTMLObject(string urlBase, int msgType)
        {
            string strUlr = urlBase;
            if (string.IsNullOrEmpty(strUlr))
            {
                return "";
            }
            else
            {
                httpItem.URL = strUlr;
                httpItem.Method = "get";
                httpItem.ResultType = ResultType.Byte;

                HttpResult result = httpClient.GetHtml(httpItem);
                if (result.CookieCollection != null && result.CookieCollection.Count != 0)
                {
                    httpItem.CookieCollection.Add(result.CookieCollection);
                }

                if (result.ResultByte != null)
                {
                    using (Stream stream = new MemoryStream(result.ResultByte))
                    {
                        stream.Write(result.ResultByte, 0, result.ResultByte.Length);
                        String str = "";

                        if (msgType == 3 || msgType == 47)
                        {
                            Image image = Image.FromStream(stream);
                            if (image != null)
                            {
                                string exName = GetImageExtension(image);
                                str = @"\image\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "." + exName;
                                image.Save(System.Environment.CurrentDirectory + str, image.RawFormat);
                            }
                        }
                        else if (msgType == 34)
                        {
                            str = @"\voice\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".mp3";
                            File.WriteAllBytes(System.Environment.CurrentDirectory + str, result.ResultByte);
                        }
                        else if (msgType == 62)
                        {
                            str = @"\video\" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".flv";
                            File.WriteAllBytes(System.Environment.CurrentDirectory + str, result.ResultByte);
                        }

                        return str;
                    }
                }

                return "";
            }

        }

        /// <summary>
        /// 根据图形获取图形的扩展名 
        /// </summary>
        /// <param name="p_Image">图形</param>
        /// <returns>扩展名</returns>
        private static string GetImageExtension(Image p_Image)
        {
            Type Type = typeof(System.Drawing.Imaging.ImageFormat);
            System.Reflection.PropertyInfo[] _ImageFormatList = Type.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            for (int i = 0; i != _ImageFormatList.Length; i++)
            {
                System.Drawing.Imaging.ImageFormat _FormatClass = (System.Drawing.Imaging.ImageFormat)_ImageFormatList[i].GetValue(null, null);
                if (_FormatClass.Guid.Equals(p_Image.RawFormat.Guid))
                {
                    return _ImageFormatList[i].Name;
                }
            }
            return "";
        }
        /// <summary>
        /// 对消息内的连接进行转义替换
        /// </summary>
        /// <param name="url">原始连接</param>
        /// <returns>转义字符替换后的连接</returns>
        private static string URLDecode(string url)
        {
            url = url.Replace("&quot;", "\"");
            url = url.Replace("&amp;", "&");
            url = url.Replace("&lt;", "<");
            url = url.Replace("&gt;", ">");
            url = url.Replace("&nbsp;", " ");
            return url;
        }

        /// <summary>
        /// 自己的消息处理函数
        /// </summary>
        /// <param name="msgObj">要进行处理的消息</param>
        private static void Handle_msg(WXMsg.WebWXSyncObj msgObj)
        {
            if (msgObj.AddMsgCount != 0 && msgObj.AddMsgList != null)
            {
                foreach (WXMsg.AddMsgList oneMsg in msgObj.AddMsgList)
                {
                    MemberObj fUser = FindMemberInfoById(oneMsg.FromUserName);

                    string msgInfo = "自己的消息处理函数收到{0}的消息:{1}";
                    if (fUser != null)
                    {
                        msgInfo = string.Format(msgInfo, fUser.NickName, oneMsg.Content);
                    }
                    else
                    {
                        msgInfo = string.Format(msgInfo, oneMsg.FromUserName, oneMsg.Content);
                    }
                    // WriteLog(msgInfo);

                    //区分消息
                    WXItinMsg rs = GetWXMsgFormOriMsg(oneMsg);
                    //  string asdf = @"@920c680a387c266be85fb7eefd5b7af066554d43f2c2672e5a88ba74e43cb000";
                    //  string asdf1 = @"@a5a36645e997c526b596d4f1a3f37182167f5d5d5bd22ca74d6c63828317dbc3";
                    //  SendMsg("zailai", asdf1, asdf, 1,Uin);
            //        SendOnlog(msgInfo);
                    if (rs != null && !string.IsNullOrEmpty(rs.From) == false && !string.IsNullOrEmpty(rs.Msg) && !string.IsNullOrEmpty(rs.From2))
                    {

                        //自动回复
                        if (WXsql.AllAutoMsg != null && WXsql.AllAutoMsg.ContainsKey(rs.Msg))
                        {
                            SendMsg(WXsql.AllAutoMsg[rs.Msg], UinTUser[Uin][Uin].UserName, rs.From, 1, Uin);
                            //SendMsg(WXsql.AllAutoMsg[rs.Msg], TUser[Uin].UserName, rs.From2, 1, Uin);
                        }
                        ///保存消息
                        WXsql.DoSave(rs);
                    }
                }
            }
        }

        /// <summary>
        ///信息接收 处理
        /// </summary>
        public  static void Proc_msg(string uinmsg)
        {
            while (true)
            {
                ///如果线程要结束，就退出
                if (isStop)
                {
                    break;
                }

                ///计时开始
                System.Diagnostics.Stopwatch stop = new System.Diagnostics.Stopwatch();
                stop.Start();

                ///循环检查有没有消息
                int[] rs = Sync_check(uinmsg);
                if (rs[0] == 1100)// 从微信客户端上登出
                {
                    SendOnlog("从微信客户端上登出");
                    break;
                }
                else if (rs[0] == 1101)// 从其它设备上登了网页微信
                {
                    SendOnlog("从其它设备上登了网页微信");
                    break;
                }
                else if (rs[0] == 1102)// 从其它设备上登了网页微信
                {
                    SendOnlog("登陆的信息出现错误了,需要重新登陆一次了");
                    break;
                }
                else if (rs[0] == 0)///如果有消息就处理
                {
                    switch (rs[1])
                    {
                        case 0://"无事件"
                            break;
                        case 2://"有新消息"
                        case 3://"未知"
                        case 4://"通讯录更新"
                        case 6://"可能是红包"
                        case 7://"在手机上操作了微信"
                        default:
                            WXMsg.WebWXSyncObj msgObj = Syncmsg();
                            if (msgObj != null)
                            {
                                Handle_msg(msgObj);
                            }
                            break;
                    }
                }
                else
                {
                    SendOnlog("获得未知消息");
                }
                stop.Stop();
                TimeSpan timespan = stop.Elapsed;
                if (timespan.Milliseconds < 800)
                {
                    System.Threading.Thread.Sleep(1000 - timespan.Milliseconds);
                }
            }
        }

        #endregion

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="type"></param>
        /// <param name="Uin"></param>
        public static void SendMsg(string msg, string from, string to, int type, string Uin)
        {
            string BaseRequeststr = string.Format("{{" +
            "\"BaseRequest\":{{" +
                "\"DeviceID\" : \"{0}\"," +
                "\"Sid\" : \"{1}\"," +
                "\"Skey\" : \"{2}\"," +
                "\"Uin\" : \"{3}\"" +
            "}},", BaseRequestList[Uin]["DeviceID"].ToString(), BaseRequestList[Uin]["Sid"].ToString(), BaseRequestList[Uin]["Skey"].ToString(), BaseRequestList[Uin]["Uin"].ToString());
            //{"BaseRequest":{"DeviceID" : "e942350031118103","Sid" : "D1tGF4sar2q5eiZ9","Skey" : "@crypt_70e9c00f_54a9f5ffe37be499e7c964dc5c2fbfa1","Uin" : "3312709003"},
            string msgjson = string.Format(
            "\"Msg\" : {{" +
                "\"ClientMsgId\" : {0}," +
                "\"Content\" : \"{1}\"," +
                "\"FromUserName\" : \"{2}\"," +
                "\"LocalID\" : {3}," +
                "\"ToUserName\" : \"{4}\"," +
                "\"Type\" : {5}" +
            "}}," +
            "\"Scene\" : {6}" +
            "}}", DateTime.Now.Millisecond, msg, from, DateTime.Now.Millisecond, to, type, 0);
            //        "Msg" : { "ClientMsgId" : 1,"Content" : "超市1","FromUserName" : "@144d81d443e5f64bb4b0f848e45ff1a0bd06ac140a0e678145f51b8c230937b9","LocalID" :
            //1,"ToUserName" : "@7df659645aecfb1bc4661d7bfa18da916825ad4884a900740161876efc14b7cd","Type" : 1},"Scene" : 0}
            //5aecfb1bc4661d7bfa18da916825ad4884a900740161876efc14b7cd","Type" : 1},"Scene" : 0}3164443199
            if (Sid != null && Uin != null)
            {
                string bytes = HTTP.Post(string.Format("https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?lang=zh_CN&pass_ticket={0}", Pass_ticketList[Uin].ToString()), BaseRequeststr + msgjson, null, Uin);
                //  string send_result = Encoding.UTF8.GetString(bytes);
            }

        }

    }
}
